package com.liuyang.second.concurrency.chapter6;

public class ReadWriteLock {
    private int reading = 0;
    private int waitingReaders = 0;
    private int writing = 0;
    private int waitingWriters = 0;

    private boolean preferWriter;

    public ReadWriteLock(){
        this(true);
    }
    public ReadWriteLock(boolean preferWriter){
        this.preferWriter = preferWriter;
    }

    public synchronized void readLock() {
        this.waitingReaders++;
        try {
            while (writing > 0 || (preferWriter && waitingWriters>0)) {
                this.wait();
            }
            this.reading++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.waitingReaders--;
        }
    }

    public synchronized void readUnlock(){
        this.reading--;
        this.notifyAll();
    }

    public synchronized void writeLock(){
        this.waitingWriters++;
        try {
            while (reading>0 || writing>0){
                this.wait();
            }
            this.writing++;
        }catch (Exception e){

        }finally {
            this.waitingWriters--;
        }
    }

    public synchronized void writeUnlock(){
        this.writing--;
        this.notifyAll();;
    }
}


